package com.javaDemo.node;

public class Link{
    public static ListNode MergeOrderedList(ListNode first,ListNode head){
        ListNode cur1 = first;
        ListNode cur2 = head;
        ListNode result = new ListNode();
        result = null;
        ListNode tail = null;
        ListNode next = null;
        while((cur1 != null)  &&  (cur2 != null)){
            if(cur1.data <= cur2.data){
                if(result != null){   //当结果链表不为空时
                    next = cur1.next;  // 保存链表1的下一个节点，让循环可以继续
                    tail.next = cur1;   // 插入过程
                    cur1.next = null;
                    tail = cur1;  //保存结果链表的最后一个节点
                    cur1 = next;
                }else{   // 结果链表为空时
                    next = cur1.next;
                    result = cur1;
                    cur1.next = null;
                    //保存新的最后一个节点
                    tail = cur1;
                    cur1 = next;

                }
            }else{
                if(result != null){
                    next = cur2.next;
                    tail.next = cur2;
                    cur2.next = null;
                    tail = cur2;
                    cur2 = next;
                }else{
                    next = cur2.next;
                    result = cur2;
                    cur2.next = null;
                    //保存新的最后一个节点
                    tail = cur2;
                    cur2 = next;
                    }
            }
        }
        //其中一个链表为空之后
            if(cur1 == null){
                tail.next = cur2;
            }
            if(cur2 == null){
                tail.next = cur1;
            }

        return result;
    }
    public static void print(ListNode head){
        while(head != null){
            System.out.println(head.data);
            head = head.next;
        }
   }
    public static void main(String[] args) {
        ListNode n1 = new ListNode();
        ListNode n2 = new ListNode();
        ListNode n3 = new ListNode();
        ListNode n4 = new ListNode();
        n1.data = 1;
        n2.data = 2;
        n3.data = 3;
        n4.data = 4;
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        ListNode n5 = new ListNode();
        ListNode n6 = new ListNode();
        ListNode n7 = new ListNode();
        ListNode n8 = new ListNode();
        n5.data = 1;
        n6.data = 6;
        n7.data = 7;
        n8.data = 8;
        n5.next = n6;
        n6.next = n7;
        n7.next = n8;
        MergeOrderedList(n1,n5);
        print(n1);
    }
}